const express = require("express");
const path = require("path");
const axios = require("axios");

const { createNonceStr, createTimestamp } = require("./utils/index.js");

const app = express();

// 静态资源托管
app.use(express.static(path.resolve(__dirname, "./public")));

// 提供一个接口，用于获取 JSSDK 的签名
app.get("/api/jssdk", (req, res) => {
  // 计算 signature
  //    1. noncestr 字符串
  //    2. jsapi_ticket 票据
  //    3. timestamp 时间戳
  //    4. url       前端网页url地址，PS: 不能包含 # 以及后面的部分
  const noncestr = createNonceStr();
  const jsapi_ticket =
    "kgt8ON7yVITDhtdwci0qeVC3iHRHKpHD2Xdhic2e1ZZYerfQSsYMkJhvO2VX3K6yFLkx3R8bXGGBLakLPuFriw";
  const timestamp = createTimestamp();
  const url = req.query.url;

  // 对上述四个数组做字典序排序组装成一个字符串 key1=value1&key2=value2
  const string = `jsapi_ticket=${jsapi_ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${url}`;

  // 对 string 做 sha1 的加密，得到的内容就是 signature
  const sha1 = require("sha1");
  const signature = sha1(string);

  res.send({
    appId: "wx9c1cc1eb2938caa8",
    timestamp: timestamp,
    nonceStr: noncestr,
    signature: signature,
  });
});

// 提供一个接口，用于获取网页授权之后的用户信息
app.get("/api/login", async (req, res) => {
  // 1. 获取前端传递过来的 code
  const code = req.query.code;

  // 2. 调用微信的接口
  /**
   * {
        "access_token": "72_Pz3aOmywF8ARD5jFMnhxkWWRH-KR6SqrYVnWAxmzUZ0rlxPuLKHfEhxBQ814oDNhaR3fKW1WFBDauC_DZrz6HnejbGIjkPiaxYSvPCLhdsA",
        "expires_in": 7200,
        "refresh_token": "72_4rVA-ayhSqXiJTFCqcHHOR5FhNTf1-NX2cfsMgDJr170yb9yXCO8aSLwEv5M8mpy8CRUC14vCKUnZPBr5y9ysB1mb564HmpKcETiH96PMfs",
        "openid": "onPQ5wFQ_mFA15RzxGoazVVjuekk",
        "scope": "snsapi_userinfo"
    }
   */
  const { data } = await axios.get(
    "https://api.weixin.qq.com/sns/oauth2/access_token",
    {
      params: {
        appid: "wx9551c38135f5192e",
        secret: "3bd2edc541561c5716c87b89d790d435",
        code: code,
        grant_type: "authorization_code",
      },
    }
  );

  console.log("data.access_token", data);

  // 3. 获取用户的信息
  const { data: userinfo } = await axios.get(
    "https://api.weixin.qq.com/sns/userinfo",
    {
      params: {
        access_token: data.access_token,
        openid: data.openid,
        lang: "zh_CN",
      },
    }
  );

  res.send(userinfo);
});

app.listen(5173, () => {
  console.log("服务启动成功");
});
